package main

import (
	"errors"
	"fmt"
	"github.com/astaxie/beego/config"
	"logagent/tailf"
)

var appConfig *Configs

type Configs struct {
	logLevel string
	logPath  string

	chansize int
	kafkaconf string
	collect  []tailf.CollectConf
}

func loadConfig(configtype, filename string) (err error) {

	conf, err := config.NewConfig(configtype, filename)

	if err != nil {
		fmt.Println("new config failed,errr:", err)
		return
	}
	appConfig = &Configs{}
	appConfig.logLevel = conf.String("logs::log_level")
	if len(appConfig.logLevel) == 0 {
		appConfig.logLevel = "debug"
	}

	appConfig.logPath = conf.String("logs::log_path")
	if len(appConfig.logPath) == 0 {
		appConfig.logPath = "./conf"
	}
	appConfig.chansize, err = conf.Int("collect::chan_size")
	if err != nil {
		appConfig.chansize = 100
	}

	appConfig.kafkaconf = conf.String("kafka::server_addr")
	if len(appConfig.kafkaconf) == 0 {
		err = fmt.Errorf("invalid kafka addr")
		return
	}

	err = loadCollectConf(conf)
	if err != nil {
		fmt.Println("collect failed ,err:", err)
		return
	}
	return
}

func loadCollectConf(conf config.Configer) (err error) {

	var cc tailf.CollectConf

	cc.LogPath = conf.String("collect::path")
	if len(cc.LogPath) == 0 {
		err = errors.New("invalid collect log_path failed")
		return
	}
	cc.Topic = conf.String("collect::topic")
	if len(cc.Topic) == 0 {
		err = errors.New("invalid collect topic failed,")
		return
	}
	appConfig.collect = append(appConfig.collect, cc)
	return
}
